"use client";

import { useState, useEffect, useContext } from "react";
import keyboardData from "@/src/data/layout/k81.json";
import { KeyColor, KeyInfo } from "@/src/types/types";
import { MainContext } from "@/src/providers/MainProvider";
import KeyboardLayer from "./KeyboardLayer";
import { Box, Text, useToast, useUpdateEffect } from "@chakra-ui/react";
import _ from "lodash";

// 定义键盘按键的类型
interface KeyItem {
  row: number;
  col: number;
  x: number;
  y: number;
  h: number;
  w: number;
  code: number;
  index: number;
  name: string;
  mode: number;
}

// 添加重置图标SVG组件
const ResetIcon = () => (
  <svg
    className="w-4 h-4 mr-2"
    viewBox="0 0 24 24"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path
      d="M4 4V9H9"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
    <path
      d="M20 20V15H15"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
    <path
      d="M16.5 7.5C15.2717 6.57356 13.7096 6 12 6C8.68629 6 6 8.68629 6 12C6 13.7096 6.57356 15.2717 7.5 16.5"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
    <path
      d="M7.5 16.5C8.7283 17.4264 10.2904 18 12 18C15.3137 18 18 15.3137 18 12C18 10.2904 17.4264 8.7283 16.5 7.5"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
  </svg>
);

type KBKeyboardViewProps = {
  uiLightFactor?: number; // 0.0 - 1.0 外部可选的亮度系数（用于音频联动显示）
  uiColLevels?: number[]; // 22 列的层级（0..6），与 matrixGrid 同步
};

function KBKeyboardView({
  uiLightFactor = 0,
  uiColLevels = [],
}: KBKeyboardViewProps) {
  const {
    connectMode,
    connectedKeyboard,
    selectedKeyIndex,
    setSelectedKeyIndex,
    fnLayer,
    setFnLayer,
    keyInfos,
    setKeyInfos,
    updateKeyboardKeys,
    kbMatrix,
    macroProfiles,
    currentTab,
    profiles,
    profileIndex,
    currentLightMode,
    keyColor,
    setKeyColor,
    currentColor,
    setCurrentColor,
    multiSelectKeys,
    setMultiSelectKeys,
    updateKeyboardKeyColor,
    t,
  } = useContext(MainContext);

  const toast = useToast();

  const layoutKeys = keyboardData.layouts.keys as KeyItem[];

  // 从JSON数据中获取键盘尺寸参数
  const { width, height, bg_width, bg_height, key_scale } =
    keyboardData.layouts;

  // 添加状态用于右键菜单
  const [contextMenuPosition, setContextMenuPosition] = useState<{
    x: number;
    y: number;
  } | null>(null);

  // 自定义灯光模式的拖拽状态
  const [isDragging, setIsDragging] = useState<boolean>(false);

  // 是否在按键设置界面
  const isKeySettingTab = currentTab === "kb-keyremap";

  // 是否在自定义灯光模式
  const isCustomLightMode =
    currentTab === "kb-light" && currentLightMode === 0x0d;

  const keyClick = (index: number, event?: React.MouseEvent) => {
    // 自定义灯光模式下的按键点击处理
    if (0) {
      const newKeyColors = _.cloneDeep(keyColor); // 深拷贝当前按键信息
      newKeyColors[index] = {
        ...newKeyColors[index],
        keyColor: currentColor,
      };
      setKeyColor(newKeyColors);
      updateKeyboardKeyColor(newKeyColors);
      console.log("newKeyColors", newKeyColors);
      if (connectedKeyboard) {
        connectedKeyboard.setKeyColor(newKeyColors);
      }
      return;
    }

    setSelectedKeyIndex(index);
    const key = layoutKeys[index];
    if (key && key.name === "Fn") {
      handleFnClick(index);
    }
  };

  const drop = (evt: any, index: number) => {
    evt.preventDefault();
    const keyInfo = JSON.parse(evt.dataTransfer.getData("keyCode"));
    console.log("拖拽按键信息", keyInfo);

    const newKeyInfos = _.cloneDeep(keyInfos); // 深拷贝当前按键信息

    if (!newKeyInfos[index]) {
      // 如果按键信息不存在，创建默认的按键信息
      newKeyInfos[index] = {
        index: index,
        layer: fnLayer,
        keyValue: layoutKeys[index]?.code || 0,
        keyName: layoutKeys[index]?.name || "",
        lang: "",
        type: 0x00,
        code1: 0x00,
        code2: 0x00,
        code3: 0x00,
        fnName1: "",
        fnType: 0x00,
        fnCode1: 0x00,
        fnCode2: 0x00,
        fnCode3: 0x00,
      };
    }

    // 更新按键信息
    if (fnLayer === 1) {
      // 更新Fn层按键信息
      newKeyInfos[index] = {
        ...newKeyInfos[index],
        fnType: keyInfo.type,
        fnCode1: keyInfo.code1,
        fnCode2: keyInfo.code2,
        fnCode3: keyInfo.code3,
        fnName1: keyInfo.name, // 在Fn层设置fnName1字段
      };
    } else {
      // 更新普通层按键信息
      newKeyInfos[index] = {
        ...newKeyInfos[index],
        keyName: keyInfo.name,
        type: keyInfo.type,
        code1: keyInfo.code1,
        code2: keyInfo.code2,
        code3: keyInfo.code3,
      };
    }

    // 先更新配置文件
    updateKeyboardKeys(newKeyInfos);

    // 然后更新当前显示的按键信息
    setKeyInfos(newKeyInfos);

    // 最后更新设备
    if (connectedKeyboard) {
      try {
        console.log(`设置按键 ${index} 在层 ${fnLayer}:`, newKeyInfos[index]);
        // 这里可以调用设备的按键设置方法
        connectedKeyboard.setAllKeyInfo(newKeyInfos);
      } catch (error) {
        console.error("设置按键失败:", error);
      }
    }
  };

  const dragOver = (evt: any) => {
    evt.preventDefault();
  };

  // 处理拖动开始
  const dragStart = (evt: React.DragEvent) => {
    // 可以在这里设置拖拽的数据
    const target = evt.target as HTMLElement;
    const index = target.getAttribute("data-index");
    if (index) {
      const keyInfo = keyInfos[parseInt(index)];
      if (keyInfo) {
        evt.dataTransfer.setData(
          "keyCode",
          JSON.stringify({
            name: keyInfo.keyName,
            type: fnLayer === 1 ? keyInfo.fnType : keyInfo.type,
            code1: fnLayer === 1 ? keyInfo.fnCode1 : keyInfo.code1,
            code2: fnLayer === 1 ? keyInfo.fnCode2 : keyInfo.code2,
            code3: fnLayer === 1 ? keyInfo.fnCode3 : keyInfo.code3,
          })
        );
      }
    }
  };

  // 右键菜单处理函数
  const handleContextMenu = (evt: React.MouseEvent, index: number) => {
    evt.preventDefault();
    const keyboardElement = evt.currentTarget.closest(".keyboard");
    if (keyboardElement) {
      const rect = keyboardElement.getBoundingClientRect();
      const x = evt.clientX - rect.left;
      const y = evt.clientY - rect.top;
      setContextMenuPosition({ x, y });
      setSelectedKeyIndex(index);
    }
  };

  // 重置按键功能
  const resetKey = () => {
    if (selectedKeyIndex !== -1) {
      const newKeyInfos = _.cloneDeep(keyInfos); // 深拷贝当前按键信息

      if (!newKeyInfos[selectedKeyIndex]) {
        // 如果按键信息不存在，创建默认的按键信息
        newKeyInfos[selectedKeyIndex] = {
          index: selectedKeyIndex,
          layer: fnLayer,
          keyValue: layoutKeys[selectedKeyIndex]?.code || 0,
          keyName: layoutKeys[selectedKeyIndex]?.name || "",
          lang: "",
          type: 0x00,
          code1: 0x00,
          code2: 0x00,
          code3: 0x00,
          fnName1: "",
          fnType: 0x00,
          fnCode1: 0x00,
          fnCode2: 0x00,
          fnCode3: 0x00,
        };
      }

      // 重置按键信息
      if (fnLayer === 1) {
        // 重置Fn层按键信息 - 清空fnName1字段
        newKeyInfos[selectedKeyIndex] = {
          ...newKeyInfos[selectedKeyIndex],
          fnName1: "", // 清空Fn层按键名称
          fnType: 0x00,
          fnCode1: 0x00,
          fnCode2: 0x00,
          fnCode3: 0x00,
        };
      } else {
        // 重置普通层按键信息
        newKeyInfos[selectedKeyIndex] = {
          ...newKeyInfos[selectedKeyIndex],
          keyName: layoutKeys[selectedKeyIndex]?.name || "",
          type: 0x00,
          code1: 0x00,
          code2: 0x00,
          code3: 0x00,
        };
      }

      // 先更新配置文件
      updateKeyboardKeys(newKeyInfos);

      // 然后更新当前显示的按键信息
      setKeyInfos(newKeyInfos);

      // 最后更新设备
      if (connectedKeyboard) {
        try {
          console.log(
            `重置按键 ${selectedKeyIndex} 在层 ${fnLayer}:`,
            newKeyInfos[selectedKeyIndex]
          );
          connectedKeyboard.setAllKeyInfo(newKeyInfos);
        } catch (error) {
          console.error("重置按键失败:", error);
          toast({
            title: "重置按键失败",
            description: "无法将重置信息发送到设备",
            status: "error",
            duration: 3000,
            isClosable: true,
          });
        }
      }

      // 关闭菜单
      setContextMenuPosition(null);
      setSelectedKeyIndex(-1);
    }
  };

  // 关闭右键菜单
  const closeContextMenu = () => {
    setContextMenuPosition(null);
    setSelectedKeyIndex(-1);
  };

  // 优化层级切换处理函数
  const handleLayerChange = (layer: number) => {
    setFnLayer(layer);
    setSelectedKeyIndex(-1); // 切换层时清除选中状态
  };

  // 优化Fn键处理函数
  const handleFnKeyDown = () => {
    handleLayerChange(1);
  };

  const handleFnKeyUp = () => {
    handleLayerChange(0);
  };

  // 处理 Fn 键点击
  const handleFnClick = (index: number) => {
    const key = layoutKeys[index];
    if (key && key.name === "Fn") {
      setFnLayer(fnLayer === 0 ? 1 : 0);
    }
  };

  // 获取按键颜色的辅助函数
  const getKeyColorValue = (index: number): string => {
    const keyColorItem = keyColor[index];
    return keyColorItem?.keyColor || "rgba(255, 0, 0, 0.3)";
  };

  // 获取所有按键的音频响应颜色
  const getAllKeysAudioColors = () => {
    if (!uiColLevels || uiColLevels.length !== 22) {
      return null;
    }

    const rowsCount = 6;
    const colors: {
      [key: number]: {
        index: number;
        keyValue: number;
        keyName: string;
        keyColor: string;
      };
    } = {};

    layoutKeys.forEach((key, index) => {
      // 列映射
      const keyCenterX = (key.x + key.w / 2) * key_scale;
      const colIndex = Math.max(
        0,
        Math.min(21, Math.floor((keyCenterX / bg_width) * 22))
      );

      const level = Math.max(
        0,
        Math.min(rowsCount, uiColLevels[colIndex] ?? 0)
      );

      // 行映射（0 顶部 → rowsCount-1 底部）
      const keyCenterY = (key.y + key.h / 2) * key_scale;
      const rowIndex = Math.max(
        0,
        Math.min(
          rowsCount - 1,
          Math.floor((keyCenterY / bg_height) * rowsCount)
        )
      );

      const isOn = rowIndex >= rowsCount - level; // 与 matrixGrid 自底向上点亮一致
      const color = isOn ? "#60a5fa" : "#37415166";

      colors[index] = {
        index: key.index,
        keyValue: key.code,
        keyName: key.name,
        keyColor: color,
      };
    });

    return colors;
  };

  // 处理鼠标按下开始拖拽
  const handleKeyMouseDown = (index: number) => {
    if (isCustomLightMode) {
      setIsDragging(true);
      const newKeyColors = _.cloneDeep(keyColor); // 深拷贝当前按键信息
      newKeyColors[index] = {
        ...newKeyColors[index],
        keyColor: currentColor,
      };
      setKeyColor(newKeyColors);
      updateKeyboardKeyColor(newKeyColors);
      console.log("newKeyColors", newKeyColors);
      if (connectedKeyboard) {
        connectedKeyboard.setKeyColor(newKeyColors);
      }
    }
  };

  // 处理鼠标抬起结束拖拽
  const handleMouseUp = () => {
    if (isDragging) {
      setIsDragging(false);
    }
  };

  // 自定义灯光模式相关功能
  const handleKeyMouseEnter = (index: number) => {
    if (isCustomLightMode && isDragging) {
      const newKeyColors = _.cloneDeep(keyColor); // 深拷贝当前按键信息
      newKeyColors[index] = {
        ...newKeyColors[index],
        keyColor: currentColor,
      };
      setKeyColor(newKeyColors);
      updateKeyboardKeyColor(newKeyColors);
      console.log("newKeyColors", newKeyColors);
      if (connectedKeyboard) {
        connectedKeyboard.setKeyColor(newKeyColors);
      }
    }
  };

  // 点击键盘外部时关闭右键菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (contextMenuPosition) {
        closeContextMenu();
      }
    };

    document.addEventListener("click", handleClickOutside);
    return () => {
      document.removeEventListener("click", handleClickOutside);
    };
  }, [contextMenuPosition]);

  // 自定义灯光模式切换时清理状态
  useEffect(() => {
    if (!isCustomLightMode) {
      setMultiSelectKeys([]);
      setIsDragging(false);
    }
  }, [isCustomLightMode]);

  // 添加全局鼠标抬起事件监听
  useEffect(() => {
    document.addEventListener("mouseup", handleMouseUp);
    return () => {
      document.removeEventListener("mouseup", handleMouseUp);
    };
  }, [isDragging]);

  // 在组件中插入全局样式
  useEffect(() => {
    // 检查是否已存在样式元素
    const existingStyle = document.getElementById("kb-keyboard-styles");
    if (!existingStyle) {
      const styleElement = document.createElement("style");
      styleElement.id = "kb-keyboard-styles";
      styleElement.innerHTML = `
        @keyframes fadeIn {
          from { opacity: 0; transform: translateY(-10px); }
          to { opacity: 1; transform: translateY(0); }
        }
        .animate-fadeIn {
          animation: fadeIn 0.2s ease-out forwards;
        }
      `;
      document.head.appendChild(styleElement);
    }

    // 清理函数
    return () => {
      const styleElement = document.getElementById("kb-keyboard-styles");
      if (styleElement) {
        document.head.removeChild(styleElement);
      }
    };
  }, []);

  // 当音频列级别更新时，使用 getAllKeysAudioColors 构造 rgba 的 KeyColor[] 并通过 0xdd 下发
  useEffect(() => {
    if (!connectedKeyboard) return;
    if (!uiColLevels || uiColLevels.length !== 22) return;

    const colorMap = getAllKeysAudioColors();
    const toRgba = (color: string): string => {
      if (!color) return "rgba(0,0,0,0)";
      const s = color.trim();
      if (s.startsWith("rgba") || s.startsWith("rgb")) return s;
      if (!s.startsWith("#")) return s;
      const hex = s.replace(/^#/, "");
      const full =
        hex.length === 3
          ? hex
              .split("")
              .map((c) => c + c)
              .join("")
          : hex;
      const r = parseInt(full.slice(0, 2), 16) || 0;
      const g = parseInt(full.slice(2, 4), 16) || 0;
      const b = parseInt(full.slice(4, 6), 16) || 0;
      if (full.length === 8) {
        const a = (parseInt(full.slice(6, 8), 16) || 0) / 255;
        return `rgba(${r}, ${g}, ${b}, ${a})`;
      }
      return `rgba(${r}, ${g}, ${b}, 1)`;
    };

    const keyColors: KeyColor[] = colorMap
      ? Object.values(colorMap).map((item) => {
          return {
            index: item.index,
            keyColor: toRgba(item.keyColor),
            keyValue: item.keyValue,
            keyName: item.keyName,
          };
        })
      : [];

    (async () => {
      try {
        if (keyColors.length) {
          await connectedKeyboard.setMusicalGroove(keyColors);
        }
      } catch (e) {
        console.error("发送音乐律动 rgba 颜色失败:", e);
      }
    })();
  }, [uiColLevels, connectedKeyboard]);

  // 获取当前灯光模式的颜色
  const getKeyLightColor = (key: KeyItem, index: number) => {
    // 只在灯光设置界面显示灯光效果
    if (currentTab !== "kb-light") {
      return "transparent";
    }

    // 自定义灯光模式
    if (currentLightMode === 13) {
      // 返回按键自定义颜色或默认颜色
      return getKeyColorValue(index);
    }

    const mode = currentLightMode || 0;
    const time = Date.now() / 1000;

    // 计算按键到键盘中心的距离
    const keyboardCenterX = bg_width / 2;
    const keyboardCenterY = bg_height / 2;
    const keyCenterX = (key.x + key.w / 2) * key_scale;
    const keyCenterY = (key.y + key.h / 2) * key_scale;
    const distance = Math.sqrt(
      Math.pow(keyCenterX - keyboardCenterX, 2) +
        Math.pow(keyCenterY - keyboardCenterY, 2)
    );
    const maxDistance = Math.sqrt(
      Math.pow(keyboardCenterX, 2) + Math.pow(keyboardCenterY, 2)
    );
    const normalizedDistance = distance / maxDistance;

    // 音频响应模式：严格同步 matrixGrid 的列-行点亮逻辑
    if (uiColLevels && uiColLevels.length === 22) {
      const rowsCount = 6;
      // 列映射
      const keyCenterX = (key.x + key.w / 2) * key_scale;
      const colIndex = Math.max(
        0,
        Math.min(21, Math.floor((keyCenterX / bg_width) * 22))
      );
      const level = Math.max(
        0,
        Math.min(rowsCount, uiColLevels[colIndex] ?? 0)
      );
      // 行映射（0 顶部 → rowsCount-1 底部）
      const keyCenterY = (key.y + key.h / 2) * key_scale;
      const rowIndex = Math.max(
        0,
        Math.min(
          rowsCount - 1,
          Math.floor((keyCenterY / bg_height) * rowsCount)
        )
      );
      const isOn = rowIndex >= rowsCount - level; // 与 matrixGrid 自底向上点亮一致

      // return isOn ? "#0066ff" : "#ffffff";
      return isOn ? "#60a5fa" : "#37415166";
    }

    // 非音频响应模式：原有的灯光逻辑
    const alpha = 0.9;
    const lightnessScale = 1.0;

    // 单色常亮模式 (0x10-0x17)
    if (mode >= 0x10 && mode <= 0x17) {
      const staticColors = {
        0x10: `rgba(255, 0, 0, ${alpha})`, // 红色
        0x11: `rgba(255, 140, 0, ${alpha})`, // 橙色 - 与主题一致
        0x12: `rgba(255, 204, 0, ${alpha})`, // 黄色
        0x13: `rgba(0, 255, 0, ${alpha})`, // 绿色
        0x14: `rgba(0, 255, 255, ${alpha})`, // 青色
        0x15: `rgba(0, 0, 255, ${alpha})`, // 蓝色
        0x16: `rgba(204, 0, 255, ${alpha})`, // 紫色
        0x17: `rgba(255, 255, 255, ${alpha})`, // 白色
      };
      return staticColors[mode as keyof typeof staticColors] || "transparent";
    } else {
      const hue = (normalizedDistance * 360 + time * 30) % 360; // 颜色随距离和时间变化
      const saturation = 100; // 保持最大饱和度
      const baseLightness = Math.max(30, 70 - normalizedDistance * 40); // 中心更亮，边缘更暗
      const lightness = Math.max(
        0,
        Math.min(100, Math.round(baseLightness * lightnessScale))
      );
      return `hsla(${hue}, ${saturation}%, ${lightness}%, ${alpha})`;
    }
  };

  // 获取按键显示的名称
  const getKeyDisplayName = (keyInfo: KeyInfo, index: number) => {
    if (!keyInfo) {
      return layoutKeys[index]?.name || "";
    }

    if (fnLayer === 1) {
      // Fn层显示 - 优先显示Fn层的名称
      return keyInfo.fnName1 || layoutKeys[index]?.name || "";
    } else {
      // 普通层显示
      return keyInfo.keyName || layoutKeys[index]?.name || "";
    }
  };

  // 获取按键类型对应的文字颜色
  const getKeyTextColor = (
    keyInfo: KeyInfo,
    index: number,
    isSelected: boolean
  ) => {
    if (isSelected) {
      return "text-white font-medium";
    }

    if (layoutKeys[index]?.name === "Fn" && fnLayer === 1) {
      return "text-white font-medium";
    }

    if (!keyInfo) {
      return "text-gray-800/80 font-medium";
    }

    const currentType = fnLayer === 1 ? keyInfo.fnType : keyInfo.type;

    switch (currentType) {
      case 0x10: // 普通按键
        return "text-gray-800/80 font-medium";
      case 0x20: // 鼠标按键
        return "text-orange-600/80 font-medium";
      case 0x30: // 多媒体按键
        return "text-orange-700/80 font-medium";
      case 0x40: // 系统按键
        return "text-orange-800/80 font-medium";
      case 0x70: // 宏按键
        return "text-purple-600/80 font-medium";
      default:
        return "text-gray-700/80 font-medium";
    }
  };

  // 渲染按键
  const renderKey = (key: KeyItem, index: number) => {
    const keyInfo = keyInfos[index];
    const isSelected = isKeySettingTab && selectedKeyIndex === index;
    const lightColor = getKeyLightColor(key, index);
    const isLightMode = currentTab === "kb-light";
    const isCustomSelected = false; // 移除多选功能
    const displayName = getKeyDisplayName(keyInfo, index);
    const textColorClass = getKeyTextColor(keyInfo, index, isSelected);

    return (
      <div
        key={index}
        className={`absolute cursor-pointer transition-all duration-200 ${
          key.name !== "Fn" && fnLayer === 0
            ? "hover:bg-orange-50/60"
            : fnLayer === 1
            ? "hover:bg-orange-100/60"
            : ""
        }`}
        style={{
          left: key.x * key_scale,
          top: key.y * key_scale,
          width: key.w * key_scale,
          height: key.h * key_scale,
          padding: "1px",
        }}
        onClick={(e) => keyClick(index, e)}
        onContextMenu={(e) => handleContextMenu(e, index)}
        onDrop={(e) => drop(e, index)}
        onDragOver={dragOver}
        onMouseDown={(e) => {
          if (key.name === "Fn") {
            handleFnKeyDown();
          } else if (isCustomLightMode) {
            handleKeyMouseDown(index);
          }
        }}
        onMouseUp={() => key.name === "Fn" && handleFnKeyUp()}
        onMouseEnter={() => handleKeyMouseEnter(index)}
        draggable={!isCustomLightMode}
        onDragStart={dragStart}
        data-index={index}
      >
        <div
          className={`h-full w-full keycap rounded-lg transition-all duration-300 ${
            isSelected
              ? "bg-orange-400/60 text-white ring-4 ring-orange-400/80"
              : isCustomSelected
              ? "bg-blue-400/60 text-white ring-2 ring-blue-400/80"
              : key.name === "Fn"
              ? fnLayer === 1
                ? "bg-red-500/70 text-white"
                : "bg-red-100/60"
              : isLightMode
              ? "bg-transparent"
              : "bg-white/15 hover:bg-white/30 backdrop-blur-[2px]"
          }`}
          style={{
            border: isSelected
              ? "2px solid rgba(255, 140, 0, 0.6)"
              : isCustomSelected
              ? "2px solid rgba(59, 130, 246, 0.8)"
              : isLightMode
              ? `2px solid ${lightColor
                  .replace("0.9)", "0.2)")
                  .replace("rgba", "rgba")
                  .replace("hsla", "hsla")}`
              : "1px solid rgba(255, 255, 255, 0.1)",
            boxShadow: isSelected
              ? "0 0 12px rgba(255, 140, 0, 0.4)"
              : isCustomSelected
              ? "0 0 8px rgba(59, 130, 246, 0.4)"
              : key.name === "Fn" && fnLayer === 1
              ? "0 2px 4px rgba(239, 68, 68, 0.1)"
              : "0 2px 4px rgba(0, 0, 0, 0.02)",
            backgroundColor: lightColor,
            backdropFilter: isLightMode ? "blur(2px)" : "blur(1px)",
            transform:
              isSelected || isCustomSelected ? "scale(1.05)" : "scale(1)",
          }}
        >
          <div
            className={`h-full w-full keycap-bg rounded-lg transition-colors duration-300 ${
              isSelected
                ? "bg-orange-400/20"
                : key.name === "Fn" && fnLayer === 1
                ? "bg-transparent"
                : isLightMode
                ? "bg-white/5"
                : "bg-white/10"
            }`}
          >
            <div
              className={`key-content h-full w-full flex items-center justify-center text-xs ${textColorClass}`}
            >
              {displayName}
            </div>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="w-full h-full flex items-center justify-center">
      <div className="flex items-center gap-6 relative">
        <div
          className="keyboard relative"
          style={{ height: `${bg_height}px`, width: `${bg_width}px` }}
        >
          <div className="keyboard-bg-outer-wrapper h-full rounded-2xl bg-white/20 backdrop-blur-md p-3 shadow-lg border border-orange-200/30">
            <div
              className="keyboard-bg-inner-wrapper h-full relative rounded-xl overflow-visible"
              style={{
                background:
                  "linear-gradient(135deg, rgba(255, 248, 235, 0.3) 0%, rgba(255, 240, 220, 0.3) 100%)",
                boxShadow: "0 4px 12px rgba(255, 140, 0, 0.1)",
              }}
            >
              {layoutKeys.map((key, index) => renderKey(key, index))}

              {/* 右键菜单 */}
              {contextMenuPosition && (
                <div
                  className="absolute z-50 bg-white shadow-xl rounded-lg border border-gray-100 overflow-hidden min-w-[160px] animate-fadeIn"
                  style={{
                    position: "absolute",
                    left: `${contextMenuPosition.x}px`,
                    top: `${contextMenuPosition.y}px`,
                    transform: "translate(-50%, -50%)",
                    boxShadow: "0 4px 20px rgba(0,0,0,0.1)",
                  }}
                  onClick={(e) => e.stopPropagation()}
                >
                  <div className="py-1">
                    <div
                      className="flex items-center px-4 py-2.5 hover:bg-orange-400/10 cursor-pointer text-gray-700 hover:text-orange-500 transition-colors duration-150"
                      onClick={resetKey}
                    >
                      <ResetIcon />
                      <span className="font-medium text-sm">{t("305")}</span>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* 层级控制器 - 非自定义灯光模式时显示 */}
        {!isCustomLightMode && (
          <KeyboardLayer
            currentLayer={fnLayer}
            t={t}
            onLayerChange={handleLayerChange}
          />
        )}
      </div>
    </div>
  );
}

export default KBKeyboardView;
